// 显示输入密码弹窗
function showModal() {
    document.getElementById('paymentModal').style.display = 'block';
    clearPassword();
}

// 显示选择支付方式弹窗
function showPaymentModal() {
    document.getElementById('paymentMethodModal').style.display = 'block';
}

// 关闭弹窗
function closeModal(event) {
    if (event.target.classList.contains('modal') || event.target.classList.contains('payment-modal') || event.target.classList.contains('close')) {
        document.getElementById('paymentModal').style.display = 'none';
        document.getElementById('paymentMethodModal').style.display = 'none';
    }
}

let password = '';

// 添加数字
function addNumber(num) {
    if (password.length < 6) {
        password += num;
        document.getElementById('password').value = password;
        updateCells();
    }
}

// 清空密码
function clearPassword() {
    password = '';
    document.getElementById('password').value = password;
    updateCells();
}

// 更新密码输入框
function updateCells() {
    for (let i = 1; i <= 6; i++) {
        document.getElementById('cell' + i).innerText = password[i - 1] ? '●' : '';
    }
}

// 支付模式（余额充值、商品直接下单支付、未支付订单支付）
let amountType = parseInt(sessionStorage.getItem("amountType"), 10);
let number = parseInt(sessionStorage.getItem("number"), 10);
if (!number){
    number = 1;
}
let balance = parseInt(sessionStorage.getItem("balance"), 10);
let price = parseInt(sessionStorage.getItem("current price"), 10);
let allPrice = number * price;

// 提交密码
function submitPassword() {
    const passwordItem = document.getElementById("password");
    passwordItem.removeAttribute("readonly");
    // 检查密码是否正确（此密码是写死的，没有分用户，只用于走个流程，非正式支付！）
    if (passwordItem.value === "123456"){
        const price = parseInt(sessionStorage.getItem("current price"),10);
        const userid = sessionStorage.getItem("userid");
        let allBalance;
        // 余额充值（当前余额与金额相加）
        if (amountType === 1) {
            allBalance =  price + balance;
            // 订单支付（当前余额减去商品单价×数量，判断余额充足）
        } else if (amountType === 2 || amountType === 3){
            if (balance >= allPrice) {
                allBalance = balance - allPrice;
            } else {
                showInfo("余额不足");
                return;
            }
        }
        // 将最终余额发给后端储存
        $.ajax({
            url:'/balance',
            method: "get",
            data: {allBalance:allBalance,id: userid},
            dataType: "text",
            success: function (data) {
                if (data === "success"){
                    showInfo("支付成功");
                    sessionStorage.setItem("balance",allBalance);
                    // 暂停2秒执行
                    setTimeout(function () {
                        // 余额充值跳转回用户页
                        if (amountType === 1) {
                            window.location.href = "user.html";
                            // 订单支付将订单信息传给后端跳转回商品页
                        } else if (amountType === 2) {
                            $.ajax({
                                url: "/orders",
                                type: "get",
                                data: {
                                    type: "add",
                                    userId: sessionStorage.getItem("userid"),
                                    goodsId: sessionStorage.getItem("id"),
                                    unitPrice: sessionStorage.getItem("current price"),
                                    number: sessionStorage.getItem("number"),
                                    price: allPrice,
                                    state: 1,
                                    dataType: "text",
                                },
                                success: function () {
                                    window.location.href = "info.html";
                                }
                            })
                            // 未支付订单支付将订单状态改为已支付跳转回用户页
                        } else if (amountType === 3) {
                            $.ajax({
                                url: "/orders",
                                type: "get",
                                data: {
                                    type: "update",
                                    userId: sessionStorage.getItem("userid"),
                                    id: sessionStorage.getItem("orderId"),
                                    state: 1
                                },
                                success: function () {
                                    window.location.href = "user.html";
                                }
                            })
                        }
                    },2000);
                    // 修改剩余库存（仅对商品未支付和直接下单）
                    if (amountType === 2 || amountType === 3) {
                        const GoodsType = sessionStorage.getItem("goodsType");
                        const residue = parseInt(sessionStorage.getItem("residue"),10);
                        const allResidue = residue - number;
                        // 根据商品状态进行不同操作（1为秒杀商品，0为普通商品）
                        if (GoodsType === "1") {
                            $.ajax({
                                url:"/goodsForAdmin",
                                type:"get",
                                data:{
                                    type:"update",
                                    name:"activitys",
                                    id:sessionStorage.getItem("id"),
                                    key:"number",
                                    value:allResidue,
                                }
                            })
                        } else if (GoodsType === "0") {
                            $.ajax({
                                url:"/goodsForAdmin",
                                type:"get",
                                data:{
                                    type:"update",
                                    name:"goods",
                                    id:sessionStorage.getItem("id"),
                                    key:"inventory",
                                    value:allResidue,
                                }
                            })
                        }
                    }
                } else {
                    showInfo("支付失败");
                }
            },
            error: function () {
                showInfo("网络错误，请重试");
            }
        })
        document.getElementById('paymentModal').style.display = 'none';
        passwordItem.setAttribute("readonly", "readonly");
    } else {
        showInfo("密码错误");
        passwordItem.setAttribute("readonly", "readonly");
        clearPassword();
    }
}

// 选择支付方式（不是真的！）
function selectPaymentMethod(method, imgSrc) {
    const selectedMethod = document.querySelector('.selected-method');
    selectedMethod.querySelector('span').textContent = method;
    selectedMethod.querySelector('img').src = imgSrc;
    selectedMethod.querySelector('img').alt = method;
    document.getElementById('paymentMethodModal').style.display = 'none';
}

// 页面加载获取支付信息
window.onload = function () {
    const goodsTitle = document.getElementById("title");
    goodsTitle.textContent = sessionStorage.getItem("goodsName");
    const goodsPrice = document.getElementById("price");
    goodsPrice.textContent = "需支付：￥" + allPrice + "元";
    const userInfo = document.getElementById("info");
    userInfo.textContent = "用户：" + sessionStorage.getItem("nickname");
}

// 取消支付（除去未支付订单仍未支付外，其余订单插入为未支付状态，暂时没做定时器也就是剩余支付时间逻辑）
function quit() {
    if (amountType === 3){
        window.history.go(-1);
        return;
    }
    $.ajax({
        url:"/orders",
        type:"get",
        data: {
            type: "add",
            userId: sessionStorage.getItem("userid"),
            goodsId: sessionStorage.getItem("id"),
            unitPrice: sessionStorage.getItem("current price"),
            number: sessionStorage.getItem("number"),
            price: allPrice,
            state: 2,
            dataType: "text",
        },
        success:function (){
            amountType === 1 ? window.location.href = "user.html" : window.location.href = "info.html";
        }
    })
}
